package com.sdy.web;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sdy.po.Company;
import com.sdy.po.Notic;
import com.sdy.service.NoticService;
import com.sdy.util.Contact;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/notic")
public class NoticController {

    @Autowired
    NoticService noticService;

    /**
     * 加载消息推送页面
     * @param model
     * @param session
     * @return
     */
    @RequestMapping("")
    public String getNoticPage(Model model, HttpSession session){
        Company contactCompany = (Company) session.getAttribute("contactCompany");
        System.out.println(contactCompany);
        List<Notic> noticList = noticService.getListByCompanyId(contactCompany.getId());
        if (noticList.size() > 0){
            model.addAttribute("hasNotic",true);
            model.addAttribute("noticList", noticList);
            return"pages/noticPage";
        }
        model.addAttribute("hasNotic",false);
        return"pages/noticPage";
    }

    /**
     * 根据传来的id查找notic
     * 如果是客户看的就标记为已读
     * @param noticId
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/getOne")
    public JSONObject getOneByNoticId(Integer noticId ,HttpSession session){
        JSONObject jsonObject  = new JSONObject();
        System.out.println("1111111111"+noticId);
        jsonObject.put("notic",noticService.getOneById(noticId));
        if (!(Boolean)session.getAttribute(Contact.IS_MANAGER)){
            noticService.markAsRead(noticId);
        }
        return jsonObject;
    }

    /**
     * 批量管理消息推送
     * @return
     */
    @RequestMapping("/batch")
    public String batchOperation(Model model){
        model.addAttribute("noticList",noticService.getAll());
        return "managePages/batch-notic";
    }

    /**
     * 发送一条推送
     * @param title
     * @param info
     * @param state
     * @param authority
     * @return
     */
    @ResponseBody
    @RequestMapping("/send")
    public Boolean sendNotic(String title, String info, String state, String authority){

        return noticService.sendNotic(new Notic(title,info,state,Contact.NOTIC_READSTATE_UNREAD,new Date()),authority);
    }
}
